package com.ruoyi.net.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.XmlUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.net.domain.NetElement;
import com.ruoyi.net.netconf.Device;
import com.ruoyi.net.netconf.util.DeviceManager;
import com.ruoyi.net.service.INetElementService;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.net.mapper.ElementPortLoopbackMapper;
import com.ruoyi.net.domain.ElementPortLoopback;
import com.ruoyi.net.service.IElementPortLoopbackService;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 网元-接口-loopback配置Service业务层处理
 * 
 * @author net
 * @date 2024-11-17
 */
@Service
public class ElementPortLoopbackServiceImpl implements IElementPortLoopbackService 
{
    @Autowired
    private ElementPortLoopbackMapper elementPortLoopbackMapper;
    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private INetElementService netElementService;

    @Autowired
    private DeviceManager deviceManager;

    /**
     * 查询网元-接口-loopback配置
     * 
     * @param id 网元-接口-loopback配置主键
     * @return 网元-接口-loopback配置
     */
    @Override
    public ElementPortLoopback selectElementPortLoopbackById(String id)
    {
        return elementPortLoopbackMapper.selectElementPortLoopbackById(id);
    }

    /**
     * 查询网元-接口-loopback配置列表
     * 
     * @param elementPortLoopback 网元-接口-loopback配置
     * @return 网元-接口-loopback配置
     */
    @Override
    public List<ElementPortLoopback> selectElementPortLoopbackList(ElementPortLoopback elementPortLoopback)
    {
        if (StringUtils.isNotEmpty(elementPortLoopback.getElementId())){
            //1、读取设备 2、与数据库对比（设备连上，且库中有数据就更新激活状态）
            List<ElementPortLoopback> readLoopbacks = readDevice(elementPortLoopback);
            List<ElementPortLoopback> dataSourceBacks = elementPortLoopbackMapper.selectElementPortLoopbackList(elementPortLoopback);
            List<ElementPortLoopback> uncommonElements = readLoopbacks.stream().filter(dataSourceBack -> dataSourceBacks.stream().noneMatch(readBack -> !StringUtils.equals(readBack.getLoopbackId(), dataSourceBack.getLoopbackId()))).collect(Collectors.toList());
            for (ElementPortLoopback back:uncommonElements){
                ElementPortLoopback elementPortLoopback1 = new ElementPortLoopback();
                elementPortLoopback1.setStatus("1");
                BeanUtils.copyProperties(back,elementPortLoopback1);
                elementPortLoopback1.setId(IdUtils.simpleUUID());
                elementPortLoopback1.setElementId(elementPortLoopback.getElementId());
                elementPortLoopback1.setCreateBy(SecurityUtils.getUsername());
                elementPortLoopback1.setCreateTime(DateUtils.getNowDate());
                elementPortLoopbackMapper.insertElementPortLoopback(elementPortLoopback1);
            }
        }

        return  elementPortLoopbackMapper.selectElementPortLoopbackList(elementPortLoopback);
    }

    /**
     * 读取设备端口
     * @param elementPortLoopback
     * @return
     */
    private List<ElementPortLoopback> readDevice(ElementPortLoopback elementPortLoopback) {
        List<ElementPortLoopback> elementPortLoopbacks = new ArrayList<>();
        StringBuilder xml = new StringBuilder();
        xml.append("<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                "    <interfaces>" +
                "      <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
                "        <type>LOOPBACK</type>" +
                "      </interface>" +
                "    </interfaces>" +
                "  </if>");
        NetElement netElement = netElementService.getCacheObject(elementPortLoopback.getElementId());
        // TODO: 2024/12/9 从设备获取 接口信息
        Device device = deviceManager.getDevice(netElement.getIp());
        if (device.isConnected()) {
            String rpcReply = deviceManager.getConfig(xml.toString());
            // 解析xml
            NodeList list = XmlUtils.findNetConfXmlNodes(rpcReply, "//interfaces/interface");
            if (list != null && list.getLength() > 0) {
                for (int i = 0; i < list.getLength(); i++) {
                    ElementPortLoopback entity = new ElementPortLoopback();
                    Node node = list.item(i);
                    // 通过标签名获取节点的值
                    entity.setLoopbackId(XmlUtils.getXmlLabelValue(node, "name"));
                    Node ipNode = XmlUtils.getXmlLabelNode(node, "ip");
                    Node ipAddressNode = XmlUtils.getXmlLabelNode(ipNode, "ipv4-address-list");
                    if (ipAddressNode != null) {
                        String ipv4 = XmlUtils.getXmlLabelValue(ipAddressNode, "ipv4-address");
                        entity.setIp(StringUtils.isNotEmpty(ipv4) ? ipv4.split("/")[0] : "");
                        entity.setMask(StringUtils.isNotEmpty(ipv4) ? ipv4.split("/")[1] : "");
                        entity.setIpForm(XmlUtils.getXmlLabelValue(ipAddressNode, "secondry-use"));
                    }
                    entity.setStatus("1"); // 从设备读取到的配置，设置状态为激活

                    elementPortLoopbacks.add(entity);
                }
            }
        }
        return elementPortLoopbacks;
    }


    /**
     * 新增网元-接口-loopback配置
     * 
     * @param elementPortLoopback 网元-接口-loopback配置
     * @return 结果
     */
    @Override
    public int insertElementPortLoopback(ElementPortLoopback elementPortLoopback)
    {
        String uuid = IdUtils.simpleUUID();
        if (StringUtils.isEmpty(elementPortLoopback.getId())) {
            elementPortLoopback.setId(uuid);
        }
        elementPortLoopback.setCreateBy(SecurityUtils.getUsername());
        elementPortLoopback.setCreateTime(DateUtils.getNowDate());
        elementPortLoopback.setUpdateBy(SecurityUtils.getUsername());
        elementPortLoopback.setUpdateTime(DateUtils.getNowDate());
        return elementPortLoopbackMapper.insertElementPortLoopback(elementPortLoopback);
    }

    /**
     * 修改网元-接口-loopback配置
     * 
     * @param elementPortLoopback 网元-接口-loopback配置
     * @return 结果
     */
    @Override
    public int updateElementPortLoopback(ElementPortLoopback elementPortLoopback)
    {
        elementPortLoopback.setUpdateBy(SecurityUtils.getUsername());
        elementPortLoopback.setUpdateTime(DateUtils.getNowDate());
        return elementPortLoopbackMapper.updateElementPortLoopback(elementPortLoopback);
    }

    /**
     * 批量删除网元-接口-loopback配置
     * 
     * @param ids 需要删除的网元-接口-loopback配置主键
     * @return 结果
     */
    @Override
    public int deleteElementPortLoopbackByIds(String[] ids)
    {
        return elementPortLoopbackMapper.deleteElementPortLoopbackByIds(ids);
    }

    /**
     * 删除网元-接口-loopback配置信息
     * 
     * @param id 网元-接口-loopback配置主键
     * @return 结果
     */
    @Override
    public int deleteElementPortLoopbackById(String id)
    {
        return elementPortLoopbackMapper.deleteElementPortLoopbackById(id);
    }
}
